/**
 * Created by ray on 16/12/11.
 */
import Vue from 'vue'
import Aes from '../security/aes'

// api 地址
var urls = {}
// urls.base = 'https://api.linkfun.win/h5/api/'
urls.base = 'http://127.0.0.1:18080/'
urls.test = urls.base + 'post_test'
urls.upload = urls.base + 'btsync/test'

function myConsole(json) {
  console.log(json)
}

// 异步工具类
var Promise = function () {
  this.callbacks = [];
}

Promise.prototype = {
  construct: Promise,
  resolve: function (result) {
    this.complete("resolve ", result);
  },
  reject: function (result) {
    
    this.complete("reject", result);
  },
  complete: function (type, result) {
    while (this.callbacks[0]) {
      var callBack = this.callbacks.shift()[type];
      if (typeof callBack == "function") {
        callBack(result)
      }
    }
  },
  then: function (successHandler, failedHandler) {
    this.callbacks.push({
      resolve: successHandler,
      reject: failedHandler
    });
    return this;
  }
}

module.exports = {
// 基础函数
  HttpPost: function (url, request_obj, succeedCallBack, failCallBack) {
    // 发送格式 body:{data:json}
    // 接收格式 body:{data:json}
    if (typeof request_obj != "object") {
      request_obj = {};
    }
    request_obj.timeStamp = String(Date.parse(new Date()));
    request_obj.name = String('张三');
    request_obj.sex = String(1);
    //发送数据
    //加密
    var sendJson = JSON.stringify(request_obj)
    myConsole('url:' + url + '  sendJson:  ' + sendJson);
    Vue.http.post(url, Aes.aesEncrypt(sendJson), '')
      .then(function (res) {
        if (typeof succeedCallBack == "function") {
          //解码
          var json = Aes.aesDecrypt(res.body);
          myConsole('url:' + url + '  recJson:  ' + JSON.stringify( json ));
          //json转object
          var json_obj = JSON.parse(json);
          succeedCallBack(json_obj);
        }
      }, function (res) {
        if (typeof failCallBack == "function") {
          failCallBack();
        }
      })
  },

  // 测试api
  test: function () {
    var promise = new Promise()
    var obj = {}
    this.HttpPost(urls.test, obj, function (res) {
        promise.resolve(res)
      },
      function (res) {
        promise.reject(res)
      })
    return promise
  },

  // 测试api
  upload: function () {
    var promise = new Promise()
    var obj = {}
    this.HttpPost(urls.upload, obj, function (res) {
        promise.resolve(res)
      },
      function (res) {
        promise.reject(res)
      })
    return promise
  }
  
}
